package com.fivefu.core.skyeye.event.services.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fivefu.base.common.utils.date.DateUtils;
import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.data.services.DbFfskyeyeChannelService;
import com.fivefu.core.skyeye.event.entity.DbAiScene;
import com.fivefu.core.skyeye.event.entity.DbAiSceneType;
import com.fivefu.core.skyeye.event.mapper.DbAiSceneMapper;
import com.fivefu.core.skyeye.event.services.*;
import com.fivefu.core.skyeye.event.services.callable.EditOnOff;
import com.fivefu.core.skyeye.event.utils.OkHttpClientsUtils;
import com.fivefu.core.skyeye.event.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 场景表 服务实现类
 * </p>
 *
 * @author 
 * @since 2022-07-15 13:45:56
 */
@Service
public class DbAiSceneServiceImpl extends ServiceImpl<DbAiSceneMapper, DbAiScene> implements DbAiSceneService {

    @Resource
    private DbAiSceneTypeService dbAiSceneTypeService;


    /**
     * 编辑场景
     * @param dbAiScene 场景信息
     * @param userid 操作用户编号
     */
    @Override
    public Long editScene(DbAiScene dbAiScene,String userid) {
        dbAiScene.setUpdatedBy(userid);
        dbAiScene.setUpdatedTime(LocalDateTime.now());
        if (dbAiScene.getId()!=null){
            dbAiScene.setCvType(null);
            //修改
            baseMapper.updateById(dbAiScene);
        }else {
            //新增
            UUID uuid = UUID.randomUUID();
            dbAiScene.setCode(String.valueOf(uuid));//场景标识自动生成
            dbAiScene.setCreatedBy(userid);
            dbAiScene.setCreatedTime(LocalDateTime.now());
            dbAiScene.setIsDelete(0);
            baseMapper.insert(dbAiScene);
        }
        return dbAiScene.getId();
    }

    /**
     * 开启、关闭场景
     * @param id 场景编号
     * @param userid 用户编号
     * @param enable 是否启用(0:否 1:是)
     */
    @Override
    public void enableScene(Long id,String userid,Integer enable) {
        //修改
        DbAiScene dbAiScene = new DbAiScene();
        dbAiScene.setUpdatedTime(LocalDateTime.now());
        dbAiScene.setUpdatedBy(userid);
        dbAiScene.setEnable(enable);//是否开启
        dbAiScene.setId(id);
        baseMapper.updateById(dbAiScene);
    }

    /**
     * 删除场景
     * @param id 场景编号
     * @param userid 用户编号
     */
    @Override
    public void deleteScene(Long id,String userid) {
        //修改
        DbAiScene dbAiScene = new DbAiScene();
        dbAiScene.setIsDelete(1);//是否删除
        dbAiScene.setUpdatedBy(userid);
        dbAiScene.setEnable(0);//关闭
        dbAiScene.setUpdatedTime(LocalDateTime.now());
        dbAiScene.setId(id);
        baseMapper.updateById(dbAiScene);
    }

    /**
     * 格式化场景信息
     * @param scene
     * @return
     */
    public Map<String, Object> formatScene(DbAiScene scene){
        Map<String,Object> map = JSON.parseObject(JSON.toJSONString(scene, SerializerFeature.WriteMapNullValue), Map.class);
        //是否删除
        if (scene.getIsDelete() != null){
            if (scene.getIsDelete().equals(1)){
                map.put("isDeleteCN","是");
            }else {
                map.put("isDeleteCN","否");
            }
        }
        //是否开启
        if (scene.getEnable() != null){
            if (scene.getEnable().equals(1)){
                map.put("enableCN","是");
            }else {
                map.put("enableCN","否");
            }
        }
        //是否绘制识别区域;0:否,1:是
        if(scene.getSceneArea()!= null){
            if (scene.getSceneArea().equals(1)){
                map.put("sceneAreaCN","是");
            }else {
                map.put("sceneAreaCN","否");
            }
        }
        //场景类型
        if (StrUtils.isNotNull(scene.getCvType())){
            DbAiSceneType dbAiSceneType = dbAiSceneTypeService.querySceneTypeByCvId(Integer.valueOf(scene.getCvType()));
            if (dbAiSceneType != null){
                map.put("cvTypeParam",dbAiSceneType.getCvParam());//识别特殊字段
            }
        }
        if (scene.getCreatedTime() != null){
            String time = DateUtils.format(scene.getCreatedTime(),DateUtils.DEFAULT_DATETIME_PATTERN);
            map.put("createdTime", time);
        }
        if (scene.getUpdatedTime() != null){
            String time = DateUtils.format(scene.getUpdatedTime(),DateUtils.DEFAULT_DATETIME_PATTERN);
            map.put("updatedTime", time);
        }
        return map;
    }

    /**
     * 通过编号查询场景信息
     * @param id 场景编号
     * @return
     */
    @Override
    public DbAiScene querySceneByID(Long id){
        DbAiScene scene = baseMapper.selectById(id);
        return scene;
    }

    /**
     * 获取场景详情
     * @param id 场景编号
     */
    @Override
    public Map<String, Object> querySceneDetail(Long id) {
        DbAiScene scene = querySceneByID(id);
        if (scene != null){
            Map<String, Object> map = formatScene(scene);
            return map;
        }
        return null;
    }

    /**
     * 分页获取场景列表
     * @param page 当前页
     * @param limit 每页显示条数
     * @return
     */
    @Override
    public Page<Map<String, Object>> querySceneByPage(Integer page, Integer limit) {
        Page<Map<String,Object>> backPage = new Page<>();
        List<Map<String,Object>> backList = new ArrayList<>();

        List<DbAiScene> list = new ArrayList<>();
        QueryWrapper<DbAiScene> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        if (page != null && limit != null){
            Page<DbAiScene> iPage = new Page<>(page,limit);
            iPage = baseMapper.selectPage(iPage,wrapper);
            list = iPage.getRecords();
            backPage.setTotal(iPage.getTotal());
        }else {
            list = baseMapper.selectList(wrapper);
            backPage.setTotal(list.size());
        }

        list.forEach(scene -> {
            backList.add(formatScene(scene));
        });
        backPage.setRecords(backList);

        return backPage;
    }

    /**
     * 通过识别类型编号查询识别场景信息
     * @param cvId 识别类型编号
     * @return
     */
    @Override
    public DbAiScene querySceneByCvId(Integer cvId){
        QueryWrapper<DbAiScene> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("cv_type",cvId);
        DbAiScene scene = baseMapper.selectOne(wrapper);
        return scene;
    }

    @Override
    public DbAiScene querySceneByCode(String code) {
        QueryWrapper<DbAiScene> wrapper = new QueryWrapper<>();
        wrapper.eq("code",code);
        DbAiScene dbAiScene = baseMapper.selectOne(wrapper);
        return dbAiScene;
    }

    /**
     * 查询其他的开启场景标识
     * @param code 场景唯一标识
     * @return
     */
    public List<String> getCameraCodes(String code){
        QueryWrapper<DbAiScene> wrapper = new QueryWrapper<>();
        wrapper.eq("enable",1);
        wrapper.eq("is_delete",0);
        wrapper.ne("code",code);
        wrapper.select("code");
        List<DbAiScene> dbAiScenes = baseMapper.selectList(wrapper);
        List<String> list = dbAiScenes.stream().map(k -> k.getCode()).collect(toList());
        return list;
    }

    /**
     * 查询开启的场景数据信息
     * @return
     */
    @Override
    public List<DbAiScene> queryOpenScene() {
        QueryWrapper<DbAiScene> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("enable",1);
        List<DbAiScene> sceneList = baseMapper.selectList(wrapper);
        return sceneList;
    }

    /**
     * 查询已存在的场景
     * @return
     */
    @Override
    public List<DbAiScene> queryScene() {
        QueryWrapper<DbAiScene> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        List<DbAiScene> sceneList = baseMapper.selectList(wrapper);
        return sceneList;
    }


}
